<template>
  <div class="app-container">
    <div style="font-size: 14px">
      <div v-for="(item, index) in categories" :key="index">
        <span style="font-size: 12px; color: #606266">{{ item.name }}:</span>
        <el-radio-group
          v-model="queryParams[item.key]"
          style="margin: 10px 10px"
          size="mini"
        >
          <el-radio-button
            v-for="(i, ind) in item.tags"
            :key="ind"
            :label="i.value"
            >{{ i.name }}</el-radio-button
          >
        </el-radio-group>
      </div>
    </div>
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="职位ID" prop="qdkbId">
        <el-input
          type="number"
          v-model="queryParams.qdkbId"
          placeholder="请输入主键，唯一标识职位"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="职位名称" prop="positionName">
        <el-input
          v-model="queryParams.positionName"
          placeholder="请输入职位名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="品牌名称" prop="brandName">
        <el-input
          v-model="queryParams.brandName"
          placeholder="请输入品牌名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="职位行业" prop="industry">
        <el-cascader
          clearable
          filterable
          :props="{
            emitPath: false,
          }"
          :show-all-levels="false"
          v-model="queryParams.industry"
          :options="industrys"
        ></el-cascader>
      </el-form-item>
      <el-form-item label="岗位城市" prop="jobCity">
        <el-cascader
          clearable
          filterable
          :props="{
            emitPath: false,
          }"
          :show-all-levels="false"
          v-model="queryParams.jobCity"
          :options="regionData"
        ></el-cascader>
      </el-form-item>
      <el-form-item label="销售城市" prop="salesCity">
        <el-cascader
          clearable
          filterable
          :props="{
            emitPath: false,
          }"
          :show-all-levels="false"
          v-model="queryParams.salesCity"
          :options="regionData"
        ></el-cascader>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-table
      v-loading="loading"
      :data="qdkbList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="公司名称" align="center" width="270">
        <template slot-scope="scope">
          <div class="company" @click="seeqdkb(scope.row.qdkbId)">
            <div class="left">
              <img
                :src="scope.row.picUrl ? baseUrl + scope.row.picUrl : c"
                :width="80"
                :height="80"
                alt="职位图片"
              />
              <div class="pro">
                {{ scope.row.combinedInfo.employmentType }}
              </div>
              <div class="id">{{ scope.row.combinedInfo.id }}</div>
            </div>
            <div class="right">
              <div class="titlename">
                {{ scope.row.combinedInfo.positionName }}
              </div>
              <div class="brand">
                {{ scope.row.combinedInfo.brandName }}
              </div>
              <div>
                <el-tag type="danger" v-if="scope.row.interviewdeadline == 'Y'"
                  >面试已截至</el-tag
                >
              </div>
              <div>
                <el-tag type="info" v-if="scope.row.isFull == 'Y'"
                  >已抢满</el-tag
                >
              </div>
            </div>
          </div>
        </template>
      </el-table-column>

      <el-table-column label="结算规则" width="500">
        <template slot-scope="scope">
          <div class="rule">
            <template v-for="(item, index) in scope.row.rebateInfoArray">
              <div v-if="item.value" :key="index" class="ellipsis">
                <span>{{ item.label }}：</span>
                <el-tooltip
                  class="item"
                  effect="dark"
                  :content="item.value"
                  placement="top-start"
                >
                  <span class="val">{{ item.value }}</span>
                </el-tooltip>
              </div>
            </template>
          </div>
        </template>
      </el-table-column>
      <el-table-column
        label="负责人"
        align="center"
        prop="positionResponsiblePerson"
      />
      <el-table-column
        label="联系PM"
        align="center"
        prop="phonenumber"
        width="200"
      />
      <el-table-column
        label="更新时间"
        align="center"
        prop="updateTime"
        width="200"
      />

      <el-table-column
        label="需求人数"
        align="center"
        prop="requiredQuantity"
      />
      <el-table-column label="约面人数" align="center">
        <template slot-scope="scope">
          {{ scope.row.aboutFaceNum || 0 }}
        </template>
      </el-table-column>
      <el-table-column label="到面人数" align="center">
        <template slot-scope="scope">
          {{ scope.row.toFaceNum || 0 }}
        </template>
      </el-table-column>
      <el-table-column label="offer人数" align="center">
        <template slot-scope="scope">
          {{ scope.row.offerNum || 0 }}
        </template>
      </el-table-column>
      <el-table-column label="入职人数" align="center">
        <template slot-scope="scope">
          {{ scope.row.entryNum || 0 }}
        </template>
      </el-table-column>
      <el-table-column
        label="已抢单TL数量"
        align="center"
        prop="recommendedOfficerCount"
      />
      <el-table-column
        label="职位面试城市"
        align="center"
        prop="interviewCity"
      />
      <el-table-column
        label="操作"
        fixed="right"
        align="center"
        width="200"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <!-- <el-button
            size="mini"
            type="text"
            icon="el-icon-s-release"
            v-hasPermi="['system:pq:pmadd']"
            @click="handleAddOrUpdate(scope.row.qdkbId)"
            >职位排期</el-button
          > -->
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="
              handleSee(scope.row.qdkbId, scope.row.positionResponsiblePerson)
            "
            v-hasPermi="['system:wdqd:listuser']"
            >查看抢单人员</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-user-solid"
            @click="handleAdd(scope.row.qdkbId)"
            v-if="scope.row.isFull == 'N'"
            v-hasPermi="['system:wdqd:add']"
            >我要抢单</el-button
          >
          <span v-if="scope.row.isFull == 'Y'">已抢满</span>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改【请填写功能名称】对话框 -->
    <!-- <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="排期周期" prop="scheduleStartDate">
          <el-date-picker
            v-model="form.startEnd"
            @change="getWeekDays()"
            :format="form.scheduleStartDate + '-' + form.scheduleEndDate"
            value-format="yyyy-MM-dd"
            type="week"
            :picker-options="{ firstDayOfWeek: 1 }"
            placeholder="选择周"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="交付顾问" prop="userIds">
          <el-select
            v-model="form.userIds"
            filterable
            multiple
            placeholder="请选择"
          >
            <el-option
              v-for="(item, index) in userList"
              :key="index"
              :label="item.userName"
              :value="item.userId"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog> -->

    <el-dialog
      :title="'负责人:  ' + positionManager"
      :visible.sync="open2"
      style="height: 80%; overflow: auto"
    >
      <el-table
        v-loading="loading"
        :data="wdqdUserList"
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          label="TL/入驻商管理员"
          align="center"
          prop="userName"
        />
        <el-table-column
          label="排期"
          align="center"
          class-name="small-padding fixed-width"
        >
          <template slot-scope="scope">
            {{ scope.row.scheduleStatus == 1 ? "已排期" : "未排期" }}
          </template>
        </el-table-column>
        <el-table-column label="抢单时间" align="center" prop="createTime" />
      </el-table>
    </el-dialog>

    <el-drawer
      title="职位信息"
      :visible.sync="open1"
      direction="ltr"
      width="40%"
    >
      <el-form label-position="left" class="demo-table-expand">
        <el-form-item label=""><h3>职位基本信息</h3></el-form-item>
        <div style="border-bottom: 1px solid #e6ebf5">
          <el-row :gutter="10" class="mb8">
            <el-col :span="12"
              ><el-form-item label="职位名称:">
                {{ qdkbData.positionName }}
              </el-form-item></el-col
            >
            <el-col :span="12"
              ><el-form-item label="用工类型:">
                {{ qdkbData.employmentType }}
              </el-form-item></el-col
            >
            <el-col :span="24"
              ><el-form-item label="品牌:">
                {{ qdkbData.brandName }}
              </el-form-item></el-col
            >
            <el-col :span="24"
              ><el-form-item label="需求入职:">
                {{ qdkbData.requiredQuantity }}人
              </el-form-item></el-col
            >
            <el-col :span="24"
              ><el-form-item label="职能:">
                {{ qdkbData.fn }}
              </el-form-item></el-col
            >
            <el-col :span="24"
              ><el-form-item label="工作地点:">
                {{ qdkbData.workAdress }}
              </el-form-item></el-col
            >
          </el-row>
        </div>
        <div style="border-bottom: 1px solid #e6ebf5">
          <el-row :gutter="10" class="mb8">
            <el-col :span="12"
              ><el-form-item label="年龄:">
                {{ qdkbData.ageRange || "不限" }}
              </el-form-item></el-col
            >
            <el-col :span="12"
              ><el-form-item label="性别:">
                {{ qdkbData.genderRequirement || "不限" }}
              </el-form-item></el-col
            >
            <el-col :span="12"
              ><el-form-item label="学历:">
                {{ qdkbData.educationRequirement || "不限" }}
              </el-form-item></el-col
            >
            <el-col :span="12"
              ><el-form-item label="工作经验:">
                {{ qdkbData.experienceRequirement || "不限" }}
              </el-form-item></el-col
            >
          </el-row>
        </div>
        <div>
          <el-row :gutter="10" class="mb8">
            <el-col :span="24"
              ><el-form-item label="面试地点:">
                {{ qdkbData.interviewAddress }}
              </el-form-item></el-col
            >
            <el-col :span="24"
              ><el-form-item label="面试时间:">
                {{ qdkbData.interviewStartDate }}
              </el-form-item></el-col
            >
            <el-col :span="24"
              ><el-form-item label="结束时间:">
                {{ qdkbData.interviewSendDate }}
              </el-form-item></el-col
            >
            <el-col :span="24"
              ><el-form-item label="工作时间:">
                {{ qdkbData.workDate }}
              </el-form-item></el-col
            >
            <el-col :span="24"
              ><el-form-item label="职位负责人:">
                {{ qdkbData.positionResponsiblePerson }}
              </el-form-item></el-col
            >
            <el-col :span="24"
              ><el-form-item label="职位负责人电话:">
                {{ qdkbData.phonenumber }}
              </el-form-item></el-col
            >
            <el-col :span="24"
              ><el-form-item label="职位参与人:">
                {{ qdkbData.positionParticipants }}
              </el-form-item></el-col
            >
            <el-col :span="24"
              ><el-form-item label="职位亮点:">
                {{ qdkbData.positionHighlights }}
              </el-form-item></el-col
            >
            <el-col :span="24"
              ><el-form-item label="职位描述:">
                {{ qdkbData.positionDescription }}
              </el-form-item></el-col
            >
            <el-col :span="24"
              ><el-form-item label="沟通要点:">
                {{ qdkbData.communicate }}
              </el-form-item></el-col
            >
          </el-row>
        </div>
        <el-form-item label=""><h3>薪资福利</h3></el-form-item>
        <div>
          <el-row :gutter="10" class="mb8">
            <el-col :span="24"
              ><el-form-item label="基本薪资:">
                {{ qdkbData.baseSalary }}
              </el-form-item></el-col
            >
            <el-col :span="24"
              ><el-form-item label="综合薪资:">
                {{ qdkbData.totalSalary }}
              </el-form-item></el-col
            >
            <el-col :span="24"
              ><el-form-item label="其他构成:">
                {{ qdkbData.salaryComponents }}
              </el-form-item></el-col
            >
            <el-col :span="24"
              ><el-form-item label="薪资备注:">
                {{ qdkbData.salaryNotes }}
              </el-form-item></el-col
            >
            <el-col :span="6"
              ><el-form-item label="提供住宿:">
                {{ qdkbData.hasHousingProvided == "Y" ? "是" : "否" }}
              </el-form-item></el-col
            >
            <el-col :span="6"
              ><el-form-item label="社保:">
                {{ qdkbData.hasSocialInsurance == "Y" ? "是" : "否" }}
              </el-form-item></el-col
            >
            <el-col :span="6"
              ><el-form-item label="商保:">
                {{ qdkbData.hasCommercialInsurance == "Y" ? "是" : "否" }}
              </el-form-item></el-col
            >
            <el-col :span="6"
              ><el-form-item label="公积金:">
                {{ qdkbData.hasHousingFund == "Y" ? "是" : "否" }}
              </el-form-item></el-col
            >
          </el-row>
        </div>
      </el-form>
    </el-drawer>
  </div>
</template>

<script>
import { listQdkbOne, getQdkb } from "@/api/system/qdkb";
import { addWdqd, listWdqdUser } from "@/api/system/wdqd";
import { listPqpmSchedule, pmScheduleAdd } from "@/api/system/pq";
import { categories, industrys, cateTab } from "@/utils/data.js"; // 根据实际路径调整
import { regionData } from "@/utils/address.js";
import dayjs from "dayjs";

import c from "@/assets/c.jpg";
export default {
  name: "Qdkb",
  dicts: ["sys_yes_no", "sys_user_sex"],
  data() {
    return {
      c,
      baseUrl: process.env.VUE_APP_BASE_API,
      categories,
      regionData,
      industrys,
      cateTab,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 岗位信息表格数据
      qdkbList: [],
      wdqdUserList: [],
      positionManager: null,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,

      open1: false,

      open2: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        qdkbId: null,
        positionName: null,
        brandName: null,
        rebateType: null,
        positionLabel: null,
        fn: null,
        parentIndustry: null,
        industry: null,
        jobCity: null,
        salesCity: null,
        employmentType: null,
        isFull: null,
        interviewdeadline: null,
      },
      form: {},
      qdkbId: "",
      userList: [],
      mapOrderIds: {},
      qdkbData: {},

      // 表单校验
      rules: {
        scheduleStartDate: [
          { required: true, message: "排期开始数据不能为空", trigger: "blur" },
        ],
        userIds: [
          { required: true, message: "用户组不能为空", trigger: "change" },
        ],
      },
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询岗位信息列表 */
    getList() {
      this.loading = true;
      listQdkbOne(this.queryParams).then((response) => {
        this.qdkbList = response.rows;
        this.qdkbList.forEach((row) => {
          row.rebateInfoArray = [
            { label: "返费类别", value: row.rebateType },
            { label: "生效日期", value: row.effectiveDate },
            { label: "返费规则", value: row.rebateRule },
            { label: "价格规则", value: row.priceRule },
            {
              label: "返费周期",
              value:
                row.rebateType != "一次性返费" ? row.refundPeriod + "月" : "",
            },
            {
              label: "返费价格",
              value: row.rebatePrice + cateTab[row.rebateType],
            },
            { label: "返费条件", value: row.rebateCondition },

            { label: "首次返费最低考勤要求", value: row.firstRefund },
            { label: "返费说明", value: row.refundExplanation },
          ];
        });
        this.qdkbList.forEach((row) => {
          row.combinedInfo = {
            id: `ID:${row.qdkbId}`,
            employmentType: row.employmentType,
            positionName: row.positionName,
            brandName: row.brandName,
          };
        });
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          const orderIds = this.form.userIds.map((v) => this.mapOrderIds[v]);
          const { scheduleStartDate, scheduleEndDate } = this.form;
          const orderIdsString = orderIds.join("_");
          const userIdsString = this.form.userIds.join("_");
          const qdkbId = this.qdkbId;
          pmScheduleAdd({
            scheduleStartDate,
            scheduleEndDate,
            orderIdsString,
            userIdsString,
            qdkbId,
          }).then((response) => {
            this.$modal.msgSuccess("成功");
            this.open = false;
            this.getList();
          });
        }
      });
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },

    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },

    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.qdkbId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },

    handleAdd(qdkbId) {
      this.$modal
        .confirm(
          "抢单后，请尽快与PM联系了解职位运作细节，启动招聘运作，如未及时运作，职位任务将强制取消"
        )
        .then(function () {
          return addWdqd({ qdkbId });
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("抢单成功");
        })
        .catch(() => {});
    },

    handleSee(qdkbId, positionResponsiblePerson) {
      this.positionManager = positionResponsiblePerson;
      listWdqdUser(qdkbId).then((res) => {
        this.wdqdUserList = res.rows;
        this.open2 = true;
      });
    },

    getWeekDays() {
      this.form.userIds = [];
      dayjs.extend(require("dayjs/plugin/isoWeek")); // 引入 weekday 插件（可选，增强周处理）
      dayjs.locale("zh-cn"); // 设置中文语言环境（包含周起始日配置）
      if (this.form.startEnd) {
        const currentDate = dayjs(this.form.startEnd);
        const monday = currentDate.isoWeekday(1); // 获取当前周的周一（1 表示周一，0 表示周日）
        this.form.scheduleStartDate = monday
          .subtract(0, "day")
          .format("YYYY-MM-DD");
        this.form.scheduleEndDate = monday.add(6, "day").format("YYYY-MM-DD");
        console.log(this.form.scheduleStartDate);
      } else {
        // 设置周起始日为周一（Day.js 默认周日为一周开始，需调整）
        const currentDate = dayjs();
        const monday = currentDate.isoWeekday(1); // 获取当前周的周一（1 表示周一，0 表示周日）
        this.form.scheduleStartDate = monday.add(0, "day").format("YYYY-MM-DD");
        this.form.scheduleEndDate = monday.add(6, "day").format("YYYY-MM-DD");
        this.form.startEnd = monday.add(1, "day").format("YYYY-MM-DD");
      }
      const { scheduleStartDate, scheduleEndDate } = this.form;
      const qdkbId = this.qdkbId;
      const pq = { scheduleStartDate, scheduleEndDate, qdkbId };
      listPqpmSchedule(pq).then((res) => {
        this.form.userIds = res.userIds;
        this.userList = res.wdqdBos;
        this.userList.forEach((v) => {
          const userId = v.userId;
          const orderId = v.orderId;
          this.mapOrderIds[userId] = orderId;
        });
      });
    },

    reset() {
      this.form = {
        userIds: null,
        scheduleStartDate: null,
        scheduleEndDate: null,
        startEnd: null,
      };
      this.resetForm("form");
    },

    handleAddOrUpdate(qdkbId) {
      this.reset();
      this.qdkbId = qdkbId;
      this.getWeekDays();
      this.open = true;
    },

    seeqdkb(qdkbId) {
      getQdkb(qdkbId).then((response) => {
        this.qdkbData = response.data;
        this.open1 = true;
      });
    },
  },
};
</script>
